<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\api\logic;



use app\common\model\ChatList;
use app\common\model\Customer;


use app\common\model\Lottery;
use GatewayClient\Gateway;
use think\Db;

/**
 * 用户接口逻辑
 */
class CustomerService extends ApiBase
{


    /***
     * 客服聊天记录
     */

    public function chat_log($data){
        $member=$this->logicApiBase->member;
        $uid=$member['id'];
        Customer::update(['is_read'=>1],['user_id'=>$uid,'is_user'=>2]);
        $list=$this->modelCustomer->getList(['user_id'=>$uid],'*','id desc');
        foreach ($list as $k =>$v){
            $list[$k]['user_image']=$v->member->avtar;
            unset($v->member);
        }
        return $list;
    }

    /***
     * 检测客服是否在线
     */
    public function check_customer(){
        Gateway::$registerAddress = getConfig('websocket_ip').':1236';
        $status=Gateway::isUidOnline(1);
        return $status;
    }


    /***
     * 绑定用户id
     */
    public function blind_user($data){
        $member=$this->logicApiBase->member;
        $uid=$member['id'];
        $client_id = $data["client_id"];
        Gateway::$registerAddress = getConfig('websocket_ip').':1236';
        Gateway::bindUid($client_id,$uid);
        Customer::where(['user_id'=>$uid,'is_user'=>2])->update(['is_read'=>1]);

    }
    /***
     * 绑定用户id
     */
    public function kefu_blind_user($data){
       // $uid=$member['id'];
        $client_id = $data["client_id"];
        Gateway::$registerAddress = getConfig('websocket_ip').':1236';
        Gateway::bindUid($client_id,1);

    }



    /**
     * 发送消息
     */
    public function  chat_message($data){
        $member=$this->logicApiBase->member;
        $uid=$member['id'];

        Db::startTrans();
        try{
            Gateway::$registerAddress = getConfig('websocket_ip').':1236';
            //$res = var_export(Gateway::getClientIdByUid($friend_id));

            $content = $data['content'];
            $message= [
                'type'=>'user_message',
                'uid'=>$uid,
                'user_name'=>$member['username'],
                'user_image'=>$member['avtar'],
                'message'=>$content,
                'time'=>date('Y-m-d H:i:s')
            ];
            $message = json_encode($message);
            $status=Gateway::isUidOnline(1);
            if($status){
                //发送消息
                Gateway::sendToUid(1, $message);

            }
            $arr=[
                'content'=> $data['content'],
                'user_id'=>$uid,
            ];
            $info=ChatList::get(['user_id'=>$uid]);
            if($info){
                $info->sort+=1;
                $info->save();
            }else{
                ChatList::create([
                    'user_id'=>$uid,
                ]);
            }
            Customer::create($arr);
                // 提交事务
            Db::commit();
            return ['avtar'=>$member->avtar,'time'=>date('Y-m-d H:i:s')];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ajaxreturn(1,$e->getMessage());
            return ajaxreturn(1,lang('可能由于网络原因'));
        }
    }

    /**
 * 客服发送消息
 */
    public function customer_message($data){

        $uid=$data['uid'];

        Db::startTrans();
        try{
            Gateway::$registerAddress = getConfig('websocket_ip').':1236';
            //$res = var_export(Gateway::getClientIdByUid($friend_id));

            $content = $data['content'];
            $message= [
                'type'=>'customer_message',
                'uid'=>$uid,
                'message'=>$content,
                'time'=>date('Y-m-d H:i:s')
            ];
            $message = json_encode($message);
            //发送消息
            $status=Gateway::isUidOnline($uid);
            if($status){
                //发送消息
                Gateway::sendToUid($uid, $message);

            }
            $arr=[
                'content'=> $data['content'],
                'user_id'=>$uid,
                'is_user'=>2
            ];
            Customer::create($arr);
            // 提交事务
            Db::commit();
            return ajaxreturn(0,lang('发送成功'));

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ajaxreturn(1,lang('可能由于网络原因'));
        }
    }

    /**
     * 客服问候
     */
    public function customer_greet(){

        $member=$this->logicApiBase->member;
        $uid=$member['id'];;


        try{
            Gateway::$registerAddress = getConfig('websocket_ip').':1236';
            //$res = var_export(Gateway::getClientIdByUid($friend_id));

            $message= [
                'type'=>'customer_message',
                'uid'=>$uid,
                'message'=>'您好！我是CCIE客服小C，很高兴为您服务，请问有什么可以帮您的？一般常见问题，直接发送出来',
                'time'=>date('Y-m-d H:i:s')
            ];
            $message1= [
                'type'=>'customer_message',
                'uid'=>$uid,
                'message'=>'您可以查看右上角的常见问题，方便您快速定位问题，以便客服快速回复您的问题',
                'time'=>date('Y-m-d H:i:s')
            ];
            $message = json_encode($message);
            $message1 = json_encode($message1);
            //发送消息
            $status=Gateway::isUidOnline($uid);
            if($status){
                //发送消息
                Gateway::sendToUid($uid, $message);
                Gateway::sendToUid($uid, $message1);

            }
            return ajaxreturn(0,lang('发送成功'));

        } catch (\Exception $e) {
            // 回滚事务
            return ajaxreturn(1,lang('可能由于网络原因'));
        }
    }



    /***
     * 客服与用户对话列表
     */

    public function  chat_user(){
        $list=ChatList::order('update_time desc,id desc')->select();
        foreach ($list as $k =>$v){
            $list[$k]['user_name']=$v->member['username'];
            $list[$k]['user_image']=$v->member->avtar;
            unset($v->member);
        }
        return $list;
    }




    /***
     * 客服与用户聊天记录
     */

    public function customer_chat_log($data){
        if(!isset($data['uid'])){
            $info=ChatList::order('update_time desc,id desc')->find();
            $uid=$info?$info['user_id']:0;
        }else{
            $uid=$data['uid'];
        }

        Customer::update(['is_read'=>1],['user_id'=>$uid,'is_user'=>1]);
        $list=$this->modelCustomer->getList(['user_id'=>$uid],'*','id asc');
        foreach ($list as $k =>$v){
            $list[$k]['user_name']=$v->member['username'];
            $list[$k]['user_image']=$v->member->avtar;
            unset($v->member);
        }
        return $list;
    }

    /***
     * 加入群组
     */
    public function join_group($data){
        // $uid=$member['id'];
        $client_id = $data["client_id"];
        Gateway::$registerAddress = getConfig('websocket_ip').':1236';
        $lottery=Lottery::get($data['id']);
        $group=$lottery['symbol'].'_'.$data['id'];
        Gateway::joinGroup($client_id,$group );

    }




}
